<template>
  <div class="sqcontent contentwidth">
    <div class="first">
      <div class="title text mian-color">标准项目意见反馈</div>
      <div class="text mian-color">
        反馈意见项目：{{ feedbackTitle }}
      </div>
    </div>
    <div class="second">
      <el-form ref="ruleFormRef"
               :model="formInline"
               :rules="formRules"
               class="demo-form-inline"
               label-width="180px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名"
                          prop="opinionPeopleName">
              <el-input  
                        v-model="formInline.opinionPeopleName"
                        placeholder="姓名"
                        clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在单位:"
                          prop="orgName">
              <el-input  
                        v-model="formInline.orgName"
                        placeholder="所在单位"
                        clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务职称:"
                          prop="position">
              <el-input  
                        v-model="formInline.position"
                        placeholder="职务职称"
                        clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业领域:"
                          prop="professionalField">
              <el-input  
                        v-model="formInline.professionalField"
                        placeholder="专业领域"
                        clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机:"
                          prop="contactTel">
              <el-input  
                        v-model="formInline.contactTel"
                        placeholder="手机"
                        clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱:"
                          prop="contactEmail">
              <el-input  
                        v-model="formInline.contactEmail"
                        placeholder="电子邮箱"
                        clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="意见内容(限500字):"
                          prop="opinionContent">
              <el-input v-model="formInline.opinionContent"
                        :rows="10"
                        :maxlength="500"
                        show-word-limit
                        type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="">
              <el-upload :file-list="fileList"
                         class="upload-demo"
                         :action="url"
                         :data="uploadData"
                          :before-upload="beforeUpload"
                           multiple 
                          style="width: 60%;"
                         	:on-success="handleUploadFileSuccess"
                         :on-preview="handlePreview"
                         :on-remove="handleRemove"
                         :limit="1" 
                         :on-exceed="handleExceed">
                <el-button type="primary">选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                  文件大小不能超过500KB.
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="">
              <el-button type="primary"
                         text
                         @click="downloadFile">意见反馈模版下载</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="third">
      <el-button type="primary"
                 @click="onSubmit"
                 round
                 style="font-size: 15px;">同意并提交征求意见</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
    import CryptoJS from "crypto-js";
  import type {
    UploadProps,
    UploadUserFile,
    FormRules,
    FormInstance,
  } from "element-plus";
  import axios from "axios";
  import { useRoute, useRouter } from "vue-router";
  import { getServerUrl } from "@/utils/url";
  const serverUrl = getServerUrl();

  const feedbackTitle = ref("");
  const formInline = reactive({
    opinionPeopleName: "",
    orgName: "",
    position: "",
    professionalField: "",
    contactTel: "",
    contactEmail: "",
    opinionContent: "",
    file: "",
    opinionFileId: "",
  });
  const uploadList = ref([]);
  const url = serverUrl + "api/files/webUpload";
  const route = useRoute();
  const router = useRouter();
  var opinionTemplateId = ref("");
  var projectInfoId = ref("");


  const uploadData = {
	timestamp: '',
	receivedToken: ''
}


const handleUploadFileSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList.value = []
		uploadList.value.push(res.data)

	} 
}



  interface ApiResponse {
    code: number;
    message: string;
    data: any; // 根据实际数据结构替换为具体类型
  }

const beforeUpload = (file) => {
  // 动态修改参数
        const timestamp = Date.now().toString();    
        const secretKey = "jkysh2jgbstandard";
	// 生成receivedToken
	const receivedToken = CryptoJS.HmacSHA256(timestamp,secretKey).toString(CryptoJS.enc.Hex);
	uploadData.timestamp = timestamp;
	uploadData.receivedToken = receivedToken;


  return true;
};
  const formRules = reactive<FormRules>({
    opinionPeopleName: [{ required: true, message: "请输入", trigger: "blur" }],
    contactTel: [
      { required: true, message: "请输入", trigger: "change" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号",
        trigger: "blur",
      },
    ],
    contactEmail: [
      { required: true, message: "请输入", trigger: "blur" },
      {
        pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
        message: "请输入正确的邮箱地址",
        trigger: "blur",
      },
    ],
    opinionContent: [{ required: true, message: "请输入", trigger: "blur" }],
  });
  const ruleFormRef = ref<FormInstance>();
  const onSubmit = async () => {
    if (!ruleFormRef.value) return;
    try {
      await ruleFormRef.value.validate();
      // 验证通过后再发送请求
      const res = await axios.post<ApiResponse>(
        serverUrl +
          "external/localStandard/opinion/submit",
        {
          projectInfoId: projectInfoId.value,
          opinionPeopleName: formInline.opinionPeopleName,
          orgName: formInline.orgName,
          position: formInline.position,
          professionalField: formInline.professionalField,
          contactTel: formInline.contactTel,
          contactEmail: formInline.contactEmail,
          opinionContent: formInline.opinionContent,
          opinionFileId: uploadList.value.length>0?uploadList.value[0].id:"",
        }
      );
      if (res.data.code === "200") {
        ElMessage.success("提交成功");
        router.back();
      }
    } catch (error) {
      // 验证失败时的处理
      console.log("表单验证失败:", error);
      return false;
    }
  };

  // 文件下载部分
  const fileList = ref<UploadUserFile[]>([
    //   {
    //     name: 'element-plus-logo.svg',
    //     url: 'https://element-plus.org/images/element-plus-logo.svg',
    //   }
  ]);

  const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  

    fileList.value = []
  };

  const handlePreview: UploadProps["onPreview"] = uploadFile => {
 
    const timestamp = Date.now();
    const secretKey = "jkysh2jgbstandard";
    // 生成receivedToken
    const receivedToken = CryptoJS.HmacSHA256(
      uploadFile.id + ":" + timestamp,
      secretKey
    ).toString(CryptoJS.enc.Hex);
    if (uploadFile.id) {
      try {
        const response = axios.get(
          `${serverUrl}api/files/webPreview`,
          {
            params: {
              fileId: uploadFile.id,
              timestamp: timestamp,
              receivedToken: receivedToken,
            },
          }
        );

        if (!response.data.data) {
          ElMessage.error("文件不存在或数据无效");
        } else if (response.data.data.url) {
          window.open(response.data.data.url, "_blank");
        } else {
          ElMessage.error("文件预览失败: 未返回有效的预览URL");
        }
      } catch (error) {
        if (error.response) {
          const errorData = error.response.data;
          ElMessage.error(errorData.message || "文件预览失败");
        } else {
          ElMessage.error("网络异常，请稍后重试");
        }
      }
    }

  };






  const downloadFile = async () => {

      // const timestamp = Date.now();
      // const secretKey = "jkysh2jgbstandard";
      // // 生成receivedToken
      // const receivedToken = CryptoJS.HmacSHA256(
      //   value.standardApprovalFileId + ":" + timestamp,
      //   secretKey
      // ).toString(CryptoJS.enc.Hex);
      try {
        const response = await axios.get(
         serverUrl + "api/files/feedbackTemplateDownload",
          {
            params: {

            },

            responseType: "blob",
          }
        );


    

        // 从响应头中提取文件名和文件类型

        const contentDisposition =
          response.headers["content-disposition"] ||
          response.headers["Content-Disposition"];
        const contentType = response.headers["content-type"];

        // 默认文件名和文件类型
        let fileName =
          getFileNameFromContentDisposition(contentDisposition) ||
          "default-filename";
        let fileExtension = "bin"; // 默认扩展名

        // 提取文件名
        // if (contentDisposition) {
        //     const match = contentDisposition.match(/filename="?(.+)"?/);
        //     if (match && match[1]) {
        //         fileName = match[1];
        //     }
        // }

        // 提取文件扩展名（根据 Content-Type）
        if (contentType) {
          const extensionMap: Record<string, string> = {
            "application/pdf": "pdf",
            "application/msword": "doc",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
              "docx",
            "application/vnd.ms-excel": "xls",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
              "xlsx",
            "image/jpeg": "jpg",
            "image/png": "png",
            "text/plain": "txt",
          };
          fileExtension = extensionMap[contentType] || fileExtension;
        }

        // 确保文件名包含正确的扩展名
        if (!fileName.includes(".")) {
          fileName = `${fileName}.${fileExtension}`;
        }

        // 创建 Blob 对象并生成下载链接
        const blob = new Blob([response.data]);
        const downloadUrl = window.URL.createObjectURL(blob);

        // 创建 <a> 标签并触发下载
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = fileName; // 使用动态生成的文件名
        document.body.appendChild(a);
        a.click();

        // 清理资源
        document.body.removeChild(a);
        window.URL.revokeObjectURL(downloadUrl);
      } catch (error) {
        console.error("文件下载失败：", error);
      }
 
  };



  const getFileNameFromContentDisposition = (contentDisposition: string) => {
    if (!contentDisposition) return null;

    // 处理标准文件名（filename="..."）
    const filenameMatch = contentDisposition.match(/filename="?(.+?)"?(;|$)/i);
    if (filenameMatch && filenameMatch[1]) {
      return decodeURIComponent(filenameMatch[1]); // 解码 URL 编码
    }

    // 处理 RFC 5987 编码的文件名（filename*=UTF-8''...）
    const filenameStarMatch = contentDisposition.match(
      /filename\*=UTF-8''(.+?)(;|$)/i
    );
    if (filenameStarMatch && filenameStarMatch[1]) {
      return decodeURIComponent(filenameStarMatch[1]); // 解码 URL 编码
    }

    return null; // 未找到文件名
  };



  const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {

  };

  const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
      `Cancel the transfer of ${uploadFile.name} ?`
    ).then(
      () => true,
      () => false
    );
  };
  onMounted(() => {
    // 类型断言
    // const id = route.params.id as string;
   
    opinionTemplateId.value = route.params.opinionTemplateId as string;
    projectInfoId.value = route.params.projectInfoId as string;
    feedbackTitle.value =route.params.id as string;
    
  });
  const downloadMB = async (val: any) => {
    if (val != "无") {
      try {
        const response = await axios.get(
          serverUrl +
            "api/files/" +
            val +
            "/downloadByFileId"
        );
        const { url, name } = response.data;
        const a = document.createElement("a");
        a.href = url;
        a.download = name;
        a.click();
        document.body.removeChild(a);
      } catch (error) {
        console.error("获取文件信息失败：", error);
      }
    } else {
      ElMessage({
        type: "error",
        message: "暂无意见反馈模板文件！",
        duration: 3000,
        showClose: false,
        center: true,
      });
    }
  };
</script>
<style lang="scss" scoped>
.sqcontent {
  margin: 20px auto 80px;
  border: 1px solid #e9eaec;
  border-color: #e9eaec;
  border-radius: 4px;
  padding: 16px;
  box-sizing: border-box;
}

.text {
  font-size: 1.42rem;
  font-weight: 700;
  text-align: center;
}

.second {
  margin-top: 20px;
}

.third {
  text-align: center;
}
</style>